import { Session } from '../src/session';
import { InMemoryProvider } from '../src/transport';
import { ToolRegistry, builtInTools } from '../src/tools';
import { InMemoryMemoryStore } from '../src/memory';

async function main() {
  console.log('🚀 Starting Chat Core Demo...\n');

  // Setup dependencies
  const provider = new InMemoryProvider();
  const tools = new ToolRegistry();
  const memories = new InMemoryMemoryStore();

  // Register built-in tools
  Object.values(builtInTools).forEach(tool => tools.register(tool));

  // Create session with tool execution enabled
  const session = new Session({
    model: provider,
    tools,
    memories,
    allowAutoTools: true
  });

  console.log('📝 Sending message: "Help me view a file"');
  const turnId = await session.send({ requestMessage: 'Help me view a file' });

  // Wait for all async processing to complete
  await new Promise(r => setTimeout(r, 200));

  const turn = session.getTurn(turnId)!;
  console.log(`\n✅ Turn completed with status: ${turn.status}`);
  console.log(`📊 Generated ${turn.nodes.length} nodes:\n`);

  // Display nodes with better formatting
  for (const [i, node] of turn.nodes.entries()) {
    console.log(`${i + 1}. [${node.type}]`);
    switch (node.type) {
      case 'RAW_RESPONSE':
        console.log(`   Text: "${(node as any).text}"`);
        break;
      case 'TOOL_USE':
        const toolNode = node as any;
        console.log(`   Tool: ${toolNode.tool}`);
        console.log(`   Input:`, toolNode.input);
        if (toolNode.result) {
          console.log(`   Result:`, toolNode.result);
        }
        if (toolNode.error) {
          console.log(`   Error: ${toolNode.error}`);
        }
        break;
      case 'AGENT_MEMORY':
        const memNode = node as any;
        console.log(`   Memory ID: ${memNode.memoryId}`);
        console.log(`   Content: "${memNode.content}"`);
        break;
      case 'SUGGESTED_QUESTIONS':
        console.log(`   Questions:`, (node as any).questions);
        break;
    }
    console.log('');
  }

  // Check memory store
  const pendingMemories = memories.listByState('pending');
  console.log(`💭 Pending memories: ${pendingMemories.length}`);
  pendingMemories.forEach(mem => {
    console.log(`   - ${mem.id}: "${mem.content}"`);
  });
}

main().catch(console.error);

